package cn.imvc.app.controllers;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import cn.imvc.app.commons.SystemConfig;
import cn.imvc.app.domains.OrderState;
import cn.imvc.app.entities.Account;
import cn.imvc.app.entities.Member;
import cn.imvc.app.entities.Orders;
import cn.imvc.app.entities.SalesReturn;
import cn.imvc.app.models.AccountModel;
import cn.imvc.app.models.CommentsModel;
import cn.imvc.app.models.MemberModel;
import cn.imvc.app.models.OrderModel;
import cn.imvc.app.models.SalesReturnModel;
import cn.imvc.app.models.SettingModel;
import cn.imvc.core.Render;
import cn.imvc.util.PageableUtils;

@Controller
@RequestMapping("buyer")
public class BuyerControllerImpl implements BuyerController {

	@Autowired
	MemberModel memberModel;

	@Autowired
	OrderModel orderModel;
	
	@Autowired
	SettingModel settingModel;

	@Autowired
	SalesReturnModel salesReturnModel;
	
	@Autowired
	private CommentsModel commentsModel;
	@Autowired
    AccountModel accountModel;

	@Autowired
	SystemConfig systemConfig;

	@RequestMapping("buyer.html")
	public String buyer(Model model, String token) {
		// 用户未登录状态直接跳转登陆页面
		if (token == null || !memberModel.checkLogin(token)) {
			return "redirect:/member/login.html";
		}
		// 通过token从缓存里取member
		Member member = memberModel.getLoginMember(token);
		member = memberModel.get(member.getId());

		model.addAttribute("key", member.getAccount().getKey1());
		return "buyer/buyer";
	}

	@RequestMapping("buyer.htm")
	public String pcbuyer(Model model, String token) {
		// 用户未登录状态直接跳转登陆页面
		if (token == null || !memberModel.checkLogin(token)) {
			return "redirect:/member/login.htm";
		}

		// 通过token从缓存里取member
		Member member = memberModel.getLoginMember(token);
		member = memberModel.get(member.getId());

		model.addAttribute("key", member.getAccount().getKey1());

		return "buyer/pcbuyer";
	}

	@RequestMapping("seller.html")
	public String seller(Model model, String token, int id) {
		// 用户未登录状态直接跳转登陆页面
		if (token == null || !memberModel.checkLogin(token)) {
			return "redirect:/member/login.html";
		}
		model.addAttribute("id", id);
		return "buyer/seller";
	}

	@RequestMapping("seller.htm")
	public String pcseller(Model model, String token, int id, String page) {
		// 用户未登录状态直接跳转登陆页面
		if (token == null || !memberModel.checkLogin(token)) {
			return "redirect:/member/login.htm";
		}
		model.addAttribute("id", id);
		model.addAttribute("page", page);
		return "buyer/pcseller";
	}

	@RequestMapping("getBuyer.html")
	public String getBuyer(Model model, String token, Integer page, Byte state) {
		// 用户未登录状态直接跳转登陆页面
		if (token == null || !memberModel.checkLogin(token)) {
			return "redirect:/member/login.html";
		}
		// 通过token从缓存里取member
		Member member = memberModel.getLoginMember(token);
		member = memberModel.get(member.getId());

		PageRequest pageRequest = PageableUtils.bulidPageRequest(page, 10, "createdAt_DESC", true);
		Page<Orders> orders = orderModel.findByState(state, member.getId(), pageRequest);
		model.addAttribute("orders", orders.getContent());
		if (orders.getTotalPages() == (page + 1)) {
			model.addAttribute("over", true);
		} else {
			model.addAttribute("over", false);
		}
		model.addAttribute("orderState", OrderState.elMap);
		model.addAttribute("state", state);
		return "buyer/buyer-list";
	}

	@RequestMapping("getBuyer.htm")
	public String pcgetBuyer(Model model, String token, Integer page, Byte state) {
		page--;
		// 用户未登录状态直接跳转登陆页面
		if (token == null || !memberModel.checkLogin(token)) {
			return "redirect:/member/login.html";
		}
		// 通过token从缓存里取member
		Member member = memberModel.getLoginMember(token);
		member = memberModel.get(member.getId());

		PageRequest pageRequest = PageableUtils.bulidPageRequest(page, 5, "createdAt_DESC", true);
		Page<Orders> orders = orderModel.findByState(state, member.getId(), pageRequest);
		model.addAttribute("orders", orders.getContent());
		model.addAttribute("count", orders.getTotalPages());
		model.addAttribute("orderState", OrderState.elMap);
		model.addAttribute("state", state);
		return "buyer/pcbuyer-list";
	}

	@RequestMapping("getSeller.html")
	public String getSeller(Model model, String token, Integer page, Byte state, int id) {
		// 用户未登录状态直接跳转登陆页面
		if (token == null || !memberModel.checkLogin(token)) {
			return "redirect:/member/login.html";
		}
		PageRequest pageRequest = PageableUtils.bulidPageRequest(page, 10, "createdAt_DESC", true);
		Page<Orders> orders = orderModel.findByState(state, id, pageRequest);
		model.addAttribute("orders", orders.getContent());
		if (orders.getTotalPages() == (page + 1)) {
			model.addAttribute("over", true);
		} else {
			model.addAttribute("over", false);
		}
		model.addAttribute("state", state);
		model.addAttribute("orderState", OrderState.elMap);

		return "buyer/seller-list";
	}

	@RequestMapping("getSeller.htm")
	public String pcgetSeller(Model model, String token, Integer page, Byte state, int id) {
		page--;
		// 用户未登录状态直接跳转登陆页面
		if (token == null || !memberModel.checkLogin(token)) {
			return "redirect:/member/login.htm";
		}
		PageRequest pageRequest = PageableUtils.bulidPageRequest(page, 5, "createdAt_DESC", true);
		Page<Orders> orders = orderModel.findByState(state, id, pageRequest);
		model.addAttribute("orders", orders.getContent());
		model.addAttribute("count", orders.getTotalPages());
		model.addAttribute("orderState", OrderState.elMap);
		model.addAttribute("state", state);

		return "buyer/pcseller-list";
	}

	@RequestMapping("/upload.html")
	@ResponseBody
	public String upload(Model model, String token, @RequestParam MultipartFile[] images) {
		Map<String, String> map = new HashMap<String, String>();
		Member member = memberModel.getLoginMember(token);
		if (member == null) {
			map.put("code", "-1");
		} else {
			String path = systemConfig.getSalesReturnImageFolder();
			map = commentsModel.upload(images, path);
		}
		return Render.json(map);
	}

	@RequestMapping("/upload.htm")
	@ResponseBody
	public String pcupload(Model model, String token, @RequestParam MultipartFile file) {
		Map<String, String> map = new HashMap<String, String>();
		Member member = memberModel.getLoginMember(token);
		if (member == null) {
			map.put("code", "-1");
		} else {
			String path = systemConfig.getSalesReturnImageFolder();
			Map<String, String> result = settingModel.upload(file, path);
			if("1".equals(result.get("code"))){
				map.put("image", result.get("fileUrl"));
				map.put("code", "1");
			}
		}
		return Render.json(map);
	}

	@RequestMapping("/salesreturn.html")
	public String salesreturn(String token, Model model, String goodsOrderIds) {
		Member member = memberModel.getLoginMember(token);
		if (member != null) {
			model.addAttribute("goodsOrderIds", goodsOrderIds);
			List<Object[]> list = salesReturnModel.findPriceByGoodsOrderIds(member, goodsOrderIds);
			Object price = list.get(0);
			model.addAttribute("price", ((BigDecimal) price).intValue());
			return "buyer/salesreturn";
		} else {
			return "redirect:/member/login.html";
		}
	}

	@RequestMapping("/addSalesReturn.html")
	@ResponseBody
	public String addSalesReturn(String token, SalesReturn salesReturn, String goodsOrderIds) {
		Member member = memberModel.getLoginMember(token);
		String[] goodsOrderIdsArray = goodsOrderIds.split(",");
		List<Integer> list = new ArrayList<Integer>();
		for (int i = 0; i < goodsOrderIdsArray.length; i++) {
			list.add(Integer.valueOf(goodsOrderIdsArray[i]));
		}
		Map<String, String> result = salesReturnModel.addSalesReturn(member, salesReturn, list);
		return Render.json(result);
	}

	@RequestMapping("/salesreturn.htm")
	public String pcsalesreturn(String token, Model model, String goodsOrderIds) {
		Member member = memberModel.getLoginMember(token);
		if (member != null) {
			model.addAttribute("goodsOrderIds", goodsOrderIds);
			List<Object[]> list = salesReturnModel.findPriceByGoodsOrderIds(member, goodsOrderIds);
			Object price = list.get(0);
			model.addAttribute("price", ((BigDecimal) price).intValue());
			return "buyer/pcsalesreturn";
		} else {
			return "redirect:/member/login.htm";
		}
	}
	
	@RequestMapping("checkPayPass.json")
	@ResponseBody
	public Map<String, Object> checkPayPass(Model model, String token,String payPass) {
		Map<String, Object> resultMap = new HashMap<String, Object>();

		// 用户未登录状态直接跳转登陆页面
		if (token == null || !memberModel.checkLogin(token)) {
			resultMap.put("code", "-1");
			resultMap.put("msg", "未登录");
			return resultMap;
		}

		// 通过token从缓存里取member
		Member member = memberModel.getLoginMember(token);
		member = memberModel.get(member.getId());
		Account account = member.getAccount();
		if (account.getPaypwd() == null || "".equals(account.getPaypwd())) {
			resultMap.put("code", "0");
			resultMap.put("msg", "请设置支付密码");
			return resultMap;
		}
		if (!accountModel.checkPayPw(account, payPass)) {
			resultMap.put("code", "0");
			resultMap.put("msg", "支付密码错误");
			return resultMap;
		}
		resultMap.put("code", "1");
		resultMap.put("msg", "成功");
		return resultMap;
	}
}
